﻿using Microsoft.EntityFrameworkCore;
using QuartzServices.Domain.Core.Models;
using QuartzServices.Domain.Interfaces;
using System.Linq.Expressions;

namespace QuartzServices.Infrastructure.Repository
{
    /// <summary>
    /// 泛型仓储
    /// </summary>
    public class Repository<TEntity> : IRepository<TEntity> where TEntity :Entity 
    {
        protected readonly MainDBContext _dbContext;

        public Repository(MainDBContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task RemoveRange(List<string> ids) 
        {
            var list = await _dbContext.Set<TEntity>().Where(d => ids.Contains(d.Id)).ToArrayAsync();
            _dbContext.Set<TEntity>().RemoveRange(list);
            await _dbContext.SaveChangesAsync();
        }


        public async Task AddRangeAsync(List<TEntity> list)
        {
            await _dbContext.Set<TEntity>().AddRangeAsync(list);
        }

        public async Task<int> CountAsync(Expression<Func<TEntity, bool>> where)
        {
            return await _dbContext.Set<TEntity>().Where(where).CountAsync();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
            GC.SuppressFinalize(this);
        }

        public async Task<List<TEntity>> PageListAsync(Expression<Func<TEntity, bool>> where, int offset, int limit)
        {
            return await _dbContext.Set<TEntity>().OrderBy(d => d.Id).Where(where).Skip(offset).Take(limit).AsNoTracking().ToListAsync();
        }
    }
}
